#!/bin/bash

set -o errexit
set -o xtrace

test_dir=$(realpath $(dirname $0))
. ${test_dir}/../functions

check_cr_config() {
    local cluster="$1"

    # apply cr config
    apply_config $test_dir/conf/$cluster.yml

    # check if at least 1 Pod started
    wait_for_running $cluster-pxc 1

    # check if statefulset created with expected config
    compare_kubectl statefulset/$cluster-pxc
    compare_kubectl statefulset/$cluster-proxysql

    # change resources
    cat_config "$test_dir/conf/$cluster.yml" \
        | sed -e 's/300m/600m/' \
        | sed -e 's/500M/1G/' \
        | sed -e 's/600M/1G/' \
        | sed -e 's/0.5G/1G/' \
        | kubectl_bin apply -f-
    sleep 2

    # check if statefulset was updated with expected config
    compare_kubectl statefulset/$cluster-pxc "-increased"
    compare_kubectl statefulset/$cluster-proxysql "-increased"

    # delete cluster
    kubectl_bin delete \
        -f $test_dir/conf/$cluster.yml
}

main() {
    create_infra $namespace
    kubectl_bin apply -f $conf_dir/secrets.yml

    desc 'check if possible to create cluster without CPU/Memory limits'
    check_cr_config "no-limits"

    desc 'check if possible to create cluster without CPU/Memory requests'
    check_cr_config "no-requests"

    desc 'check if possible to create cluster without CPU/Memory requests and limits'
    check_cr_config "no-requests-no-limits"

    destroy $namespace
}

main
